import React, { Component } from 'react';
import { Button, Card, Col, Form, Input, InputNumber, Modal, Row, Spin, Tag } from 'antd';
import { connect } from 'dva';
import PageHeaderLayout from '@/components/PageHeaderWrapper';
import SearchForm from "../../utils/searchForm";
import { pageSize, modalWidth } from "../../../config";
import tools from '../../utils';

const pageTitle = "岗位管理";
const dlgTitle = '岗位';
const reqApi = 'job';
const formItemLayout = {
  labelCol: { md: 3, xs: 7 },
  wrapperCol: { md: 21, xs: 17 },
};
const formItemLayout2 = {
  labelCol: { md: 6, xs: 8 },
  wrapperCol: { md: 18, xs: 16 },
};

class page extends Component {
  state = {
    loading: false,
    visible: false,
    dialogLoading: false,
    dialogTitle: "",
    dialogAction: "",
    searchs: [],
    editId: 0,
  };

  componentWillMount() {
    console.clear();
    this.funcGetListData();
  }

  // 表格列
  columns = [
    {
      title: '岗位名称',
      dataIndex: 'name',
      type: 'text',
    },
  ];

  // 获取列表数据
  funcGetListData = () => {
    this.setState({ loading: true });

    const { searchs } = this.state;
    const { props } = this;

    props.dispatch({
      type: reqApi + '/json',
      payload: {
        currentPage: 1,
        pageSize: 1000,
        searchs,
      },
    }).then(() => this.setState({ loading: false }));
  };

  // 记录查询表单提交
  funcOnSubmitSearch = (searchs) => {
    this.setState({ searchs }, this.funcGetListData);
  };

  // 弹出表单
  funcOpenForm = (record) => {
    const act = record ? "edit" : "create";
    this.setState({
      visible: true,
      dialogTitle: tools.funcDlgTitle(dlgTitle, act),
      dialogAction: act,
    }, () => {
      const { props } = this;
      if (act === "edit") {
        const { name, sequ, remark } = record;
        props.form.setFieldsValue({
          name,
          sequ,
          remark
        });
      } else props.form.resetFields();
    });
  };

  // 删除
  funcDelete = (e, id, name) => {
    e.preventDefault();

    Modal.confirm({
      title: '删除？',
      content: (
        <div>
          <div>你即将删除以下记录：</div>
          <div>{name}</div>
          <div>请确认是否删除？</div>
        </div>
      ),
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk: () => {
        this.setState({ loading: true });

        const { dispatch } = this.props;
        dispatch({
          type: reqApi + "/dele",
          payload: { ids: id },
        }).then(() => {
          const { props } = this;
          const { success } = props[reqApi];
          if (success) this.funcGetListData();
        });
      },
    });
  };

  // 保存
  funcSave = () => {
    const { state, props } = this;
    props.form.validateFields((error, values) => {
      if (error) return error;

      this.setState({ dialogLoading: true });

      const model = { ...values };
      if (state.dialogAction === "edit") {
        model.id = state.editId;
      }

      props.dispatch({
        type: reqApi + "/save",
        payload: {
          action: state.dialogAction,
          model,
        },
      }).then(() => {
        this.setState({ dialogLoading: false });

        const { props } = this;
        const { success } = props[reqApi];
        if (success) {
          this.setState({ visible: false });
          this.funcGetListData();
        }
      });
    });
  };

  render() {
    const { state, props } = this;
    const { getFieldDecorator } = props.form;
    const { data, total } = props[reqApi];

    return (
      <PageHeaderLayout title={pageTitle}>
        <Card bordered={false}>
          <SearchForm fields={this.columns} onSubmit={this.funcOnSubmitSearch} />
          <Button icon="plus" type="primary" onClick={() => this.funcOpenForm()}>
            {'新增' + dlgTitle}
          </Button>
          <span style={{ marginLeft: 16 }}>{'共 ' + total + ' 个岗位'}</span>
          <br />
          <br />
          <Spin spinning={state.loading}>
            {data.map((item) => {
              const { id, name } = item;
              return (
                <Tag
                  key={id}
                  closable
                  onClose={(e) => this.funcDelete(e, id, name)}
                  onClick={() => {
                    this.setState({ editId: id });
                    this.funcOpenForm(item);
                  }}
                >
                  {name}
                </Tag>
              );
            })}
          </Spin>
        </Card>

        <Modal
          width={modalWidth}
          title={state.dialogTitle}
          visible={state.visible}
          onOk={this.funcSave}
          onCancel={() => this.setState({ visible: false })}
          bodyStyle={{ paddingBottom: 0 }}
          footer={[
            <Button key="cancel" onClick={() => this.setState({ visible: false })}>
              {tools.funcDlgBtnCancel()}
            </Button>,
            <Button
              key="ok"
              type="primary"
              loading={state.dialogLoading}
              onClick={this.funcSave}>
              {state.dialogLoading ? "保存" : tools.funcDlgBtnSave()}
            </Button>,
          ]}>
          <Form>
            <Row gutter={{ md: 24, sm: 8 }}>
              <Col md={12} sm={24}>
                <Form.Item label={dlgTitle + '名称'} {...formItemLayout2}>
                  {getFieldDecorator("name", {
                    rules: [{ required: true, message: '请输入' + dlgTitle + '名称' }],
                  })(<Input maxLength={20} autoFocus />)}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="显示顺序" {...formItemLayout2}>
                  {getFieldDecorator("sequ", {
                    initialValue: 0,
                  })(<InputNumber min={0} max={1000} style={{ width: '100%' }} />)}
                </Form.Item>
              </Col>

              <Col span={24}>
                <Form.Item label="备注" {...formItemLayout}>
                  {getFieldDecorator("remark")(<Input.TextArea maxLength={255} autoSize={{ minRows: 3, maxRows: 5 }} />)}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ job }) => ({ job }))(page2);
